<template>
  <div>
    <Dialog
      ref="addModal"
      title="TCP配置"
      :width="addObj.configuration.delimeter.type === 'SplitFunc' ? 1200 : 500"
      maxHeight="auto"
      @confirm="addConfirm"
      @close="addClose"
    >
      <div class="flex justify-between">
        <el-form ref="addFormRef" :model="addObj" label-width="auto">
          <el-form-item
            label="端口"
            prop="port"
            :rules="[{ required: true, message: '端口不能为空', trigger: 'blur' }]"
          >
            <!-- <el-input v-model="addObj.port" ></el-input> -->
            <el-select v-model="addObj.port" >
              <el-option v-for="(item,index) in networkList" :key="index" :value="item.port" :label="item.port"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开启SSL" prop="configuration.useTLS">
            <el-radio-group v-model="addObj.configuration.useTLS">
              <el-radio :value="true">是</el-radio>
              <el-radio :value="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="addObj.configuration.useTLS"
            label="crt文件"
            prop="certBase64"
            :rules="[{ required: true, message: 'crt文件不能为空', trigger: 'blur' }]"
          >
            <CertificateUpload v-model="addObj.certBase64" />
            <el-input type="textarea" v-model="addObj.certBase64" show-word-limit></el-input>
          </el-form-item>
          <el-form-item
            v-if="addObj.configuration.useTLS"
            label="key文件"
            prop="keyBase64"
            :rules="[{ required: true, message: 'key文件不能为空', trigger: 'blur' }]"
          >
            <CertificateUpload v-model="addObj.keyBase64" />
            <el-input type="textarea" v-model="addObj.keyBase64" show-word-limit></el-input>
          </el-form-item>
          <el-form-item
            label="解析方式"
            prop="configuration.delimeter.type"
            :rules="[{ required: true, message: '请选择' }]"
          >
          <div class="flex justify-between w-full">
            <el-select v-model="addObj.configuration.delimeter.type" @change="parserTypeChange">
              <el-option value="NONE" label="不处理"></el-option>
              <el-option value="Delimited" label="分隔符"></el-option>
              <el-option value="FixLength" label="固定长度"></el-option>
              <el-option value="SplitFunc" label="自定义脚本"></el-option>
            </el-select>
           
          </div>
          </el-form-item>
          <el-form-item
            label="分隔符"
            prop="configuration.delimeter.delimited"
            v-if="addObj.configuration.delimeter.type === 'Delimited'"
          >
            <el-input v-model="addObj.configuration.delimeter.delimited" :maxlength="64"></el-input>
          </el-form-item>
          <!-- 固定长度 -->
          <el-form-item
            label="长度值"
            prop="configuration.delimeter.length"
            v-if="addObj.configuration.delimeter.type === 'FixLength'"
          >
            <el-input-number
              v-model="addObj.configuration.delimeter.length"
              :min="0"
              :max="60000"
            ></el-input-number>
          </el-form-item>
        </el-form>

        <!-- 自定义脚本 -->
        <div class="flex-1 ml-10px" v-if="addObj.configuration.delimeter.type === 'SplitFunc'"> 
            <el-form-item class="!mb-0" prop="configuration.delimeter.splitFunc">
              <div class="editor" :class="{ 'full-screen': fullScreen }">
                <div class="toolbars">
                  <div class="flag">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                  <div>
                    <a href="javascript:" @click="showDemo" title="查看查看样例代码与方法说明">样例</a>
                    <a href="javascript:" @click="switchFullScreen">{{fullScreen ? '退出全屏' : '全屏'}}</a>
                  </div>
                </div>
                <div class="ace-div">
                  <VAceEditor
                    ref="AceEditor"
                    v-model:value="addObj.configuration.delimeter.splitFunc"
                    lang="javascript"
                    theme="monokai"
                    :options="aceOptions"
                    class="ace-div"
                    @init="init"
                  />
                </div>
              </div>
            </el-form-item>
          </div>
        </div>
    </Dialog>
    <el-drawer
      v-model="openDrawer"
      title="说明"
      placement="right"
      size="50%"
      @close="openDrawer = false"
    >
      <Doc :type="'SplitFunc'" />
    </el-drawer>
  </div>
</template>

<script lang="jsx">
import { VAceEditor } from 'vue3-ace-editor'
import 'ace-builds/src-noconflict/ext-language_tools'
import 'ace-builds/src-noconflict/ext-searchbox'
import 'ace-builds/src-noconflict/mode-javascript'
import 'ace-builds/src-noconflict/theme-monokai';
import 'ace-builds/src-noconflict/snippets/javascript'
import { getAllNetwork } from '@/views/iot/product/api.js'
import _ from 'lodash-es'
import { newTcpAddObj } from './entity.js'
import Base from './Base.vue'

export default {
  name: 'TcpConfigAdd',
  props: {},
  mixins: [Base],
  components: {
    VAceEditor
  },
  data() {
    return {
      addObj: newTcpAddObj(),
      isEdit: false,
      fullScreen: false,
      networkList: [],
      aceOptions: {
        enableBasicAutocompletion: true, // 启用基本自动完成功能
        enableLiveAutocompletion: true, // 启用实时自动完成功能 （比如：智能代码提示）
        enableSnippets: true, // 启用代码段
        showLineNumbers: true,
        tabSize: 4,
        wrapEnabled: true,
        showPrintMargin: true,
        readOnly: false
      },
      openDrawer: false
    }
  },
  created() {},
  computed: {},
  methods: {
    open(productId) {
      if (!productId) {
        this.$message.error('请指定产品ID')
        return
      }
      this.productId = productId
      this.getNetwork(productId, newTcpAddObj()).then((data) => {
        this.isEdit = false
        if (data.id) {
          this.isEdit = true
        }
        this.addObj = data
        this.$refs.addModal.open()
      })

      this.getNetworkList()
    },
    getNetworkList() {
      getAllNetwork().then((data) => {
        this.networkList = data.result.list
      })
    },
    addClose() {
      this.addObj = newTcpAddObj()
      this.$refs.addFormRef.clearValidate()
    },
    addConfirm() {
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          const saveData = _.cloneDeep(this.addObj)
          saveData.port = parseInt(saveData.port)
          this.updateNetwork(saveData).then((resp) => {
            if (resp.success) {
              this.$message.success('操作成功')
              this.$refs.addModal.close()
              this.$emit('success')
            } else {
              this.$message.error(resp.message)
            }
          })
        }
      })
    },
    parserTypeChange(value) {
      const c = this.addObj.configuration.delimeter
      if (value === 'DIRECT') {
        c.delimited = undefined
        c.length = undefined
        c.splitFunc = undefined
      } else if (value === 'Delimited') {
        c.length = undefined
        c.splitFunc = undefined
      } else if (value === 'FixLength') {
        c.delimited = undefined
        c.splitFunc = undefined
      } else if (value === 'SplitFunc') {
        c.delimited = undefined
        c.length = undefined
        c.splitFunc = `function splitFunc(parser) {

}`
      }
    },
    showDemo() {
      this.openDrawer = true
    },
    switchFullScreen() {
      this.fullScreen = !this.fullScreen
      setTimeout(() => {
        this.editor.resize(true)
      })
    },
    init(editor) {
      // 加入自定义语法提示
      const that = this
      editor.completers = [
        {
          getCompletions: function (editor, session, pos, prefix, callback) {
            that.setCompletions(editor, session, pos, prefix, callback)
          }
        }
      ]
      this.editor = editor
    },
    setCompletions(editor, session, pos, prefix, callback) {
      if (prefix.length === 0) {
        return callback(null, [])
      } else {
        return callback(null, [
          { caption: 'parser.AddHandler()', value: 'parser.AddHandler(function(data){\n\n})' },
          { caption: 'parser.AppendResult()', value: 'parser.AppendResult(data)' },
          { caption: 'parser.Complete()', value: 'parser.Complete()' },
          { caption: 'parser.Fixed()', value: 'parser.Fixed(21)' },
          { caption: 'parser.Delimited()', value: 'parser.Delimited("\\n")' }
        ])
      }
    }
  }
}
</script>

<style lang="less" scoped>

.editor {
  height: calc(100vh - 200px);
  width: 100%;
  border-radius: 5px;
  overflow: hidden;
  .ace-div {
    height: 97%;
    width: 100%;
    line-height: 20px;
  }
  &.full-screen {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
    height: 100%;
    width: 100%;
    overflow: auto;
    .ace-div {
      height: calc(100vh - 23px);
     
    }
  }
}
.toolbars {
  background: #2F3129;
  display: flex;
  color: #a9b7c6;
  padding: 0px 10px;
  justify-content: space-between;
  border-bottom: 1px solid #5e5e5e;
  .flag{
    display: flex;
    align-items: center;
    span {
      display: block;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      margin: 0 2px;
    }
    span:nth-child(1) {
      background: #ec6a5e;
    }
    span:nth-child(2) {
      background: #f4bf4f;
    }
    span:nth-child(3) {
      background: #61c554;
    }

  }
  a {
    font-size: 12px;
    color: #a9b7c6;
    margin: 0 5px;
    text-decoration: none;
  }
}
</style>
